<?php

class ShopController extends CustomControllerAction {

    public $name = null;
    public $user = null;

    public function preDispatch() {
        parent::preDispatch();
        
        if(isset(Zend_Auth::getInstance()->getIdentity()->id))
        $userId = Zend_Auth::getInstance()->getIdentity()->id;
        $this->name = $this->getRequest()->getParam('name');
        $this->user = new DatabaseObject_User($this->db);
        $this->user->load($this->name, 'nameshop');
            if (strtotime($this->user->data_end)< strtotime(date("Y-m-d H:i:s")))
                {    
                    $this->user->plimit = '5';
                    $this->user->payflag = '0';
                    $this->user->data_end = '0000-00-00 00:00:00';
                $this->user->save();
                
                }
        $this->view->shop = $this->user;
        if(isset(Zend_Auth::getInstance()->getIdentity()->id))
        if (Zend_Auth::getInstance()->getIdentity()->id != $this->user->getId()) {
            $this->view->status = DatabaseObject_Friends::GetStatus($this->db, Zend_Auth::getInstance()->getIdentity()->id, $this->user->getId());
        }
        $cats = DatabaseObject_Products::GetCatProduct($this->db, $this->user->getId());
        $this->view->cats = $cats;
    }

    public function indexAction() {
        $this->view->page_title = "Магазин мастера";
        if (isset($_GET['sort']) && isset($_GET['order'])) {
            $sort = $_GET['sort'];
            $order = $_GET['order'];
            $_SESSION['products_sort'] = $sort . ' ' . $order;
        } elseif (!empty($_SESSION['products_sort'])) {
            $temp = explode(' ', $_SESSION['products_sort']);
            $sort = $temp['0'];
            $order = $temp['1'];
        } else {
            $sort = 'id';
            $order = 'DESC';
            $_SESSION['products_sort'] = $sort . ' ' . $order;
        }

        $cat = $this->getRequest()->getParam('cat');
        $type = $this->getRequest()->getParam('type');
        $request = $this->getRequest();
        $page = max(1, $this->getRequest()->getQuery('p'));
        $limit = $this->configuration['item_count'];
        $offset = ($page - 1) * $limit;
        $filter = array(
            'userId' => $this->user->getId(),
            'type' => $type,
            'catId' => $cat);
        $pages = ceil(DatabaseObject_Products::GetProductsCount($this->db, array('order' => $_SESSION['products_sort']), $filter) / $limit);
        $products = DatabaseObject_Products::GetProducts($this->db, array('order' => $_SESSION['products_sort'], 'limit' => $limit, 'offset' => $offset), $filter);

        $this->view->p = $page;
        $pag = CustomControllerAction::Pag($pages, $page);
        $this->view->pages = $pag;
        $this->view->products = $products;
        $this->view->cat = $cat;
        $this->view->type = $type;
        $this->view->sort = $sort;
        $this->view->order = $order;
    }

    public function requestAction() {
        $this->view->page_title = "Персональный заказ";
    }

    public function addrequestAction() {
$text = $this->getRequest()->getParam('text');
        $request = new DatabaseObject_Persorder($this->db);
        $request->of = Zend_Auth::getInstance()->getIdentity()->id;
        $request->shopId = $this->user->getId();
        $request->content = $text;
        $request->save();
          // отправим уведомление о новом заказе
       // $userNotificationConfig = new DatabaseObject_NotificationSettings($this->db);
       // $userNotificationConfig->load($this->user->getId(), 'idUser');
        
       // if($userNotificationConfig && $userNotificationConfig->new_order == 1) {
       //     DatabaseObject_User::SendNotificationEmail($this->db, 'new_person_order', $this->user->getId());
       // }
        echo "ok";
        exit;
    }

    public function itemAction() {
        $id = $this->getRequest()->getParam('id');
        $products = new DatabaseObject_Products($this->db);
        $products->load($id);
        $request = $this->getRequest();
        $fp = new FormProcessor_ProductReviews($this->db);

        $validate = $request->isXmlHttpRequest();

        if ($request->isPost()) {
            if ($validate) {
                $fp->validateOnly(true);
                $fp->process($request);
            } else if ($fp->process($request)) {
                $id = $fp->review->getId();
                $message = sprintf('Добавлен отзыв продукту "%s" пользователем "%s"', $id, Zend_Auth::getInstance()->getIdentity()->login);

                $this->writeLog($message);


                //  $this->_redirect($this->getCustomUrl(array('name'=>$this->name,'id'=>$id), 'shopproduct'));
            }
        }

        if ($validate) {
            $json = array(
                'errors' => $fp->getErrors()
            );
            $this->sendJson($json);
        } else {
            $this->view->fp = $fp;
        }

        // $text = $this->getRequest()->getPost('text');
        // $products = new DatabaseObject_Products($this->db);
        // $products->load($id);
        $tmp = explode(',', $products->material);
        foreach ($tmp as $key => $value) {
            $tmp[$key] = '<a href="' . $this->getUrl('search', 'index') . '?material=' . $value . '">' . $value . '</a>';
            // $tmp[$key] ='<a href="'.$this->getCustomUrl(array('material'=>$value), "searchmaterial").'">'.$value.'</a>';
        }
        $products->material = implode(', ', $tmp);
        $tmp = explode(',', $products->color);
        foreach ($tmp as $key => $value) {
            $tmp[$key] = '<a href="' . $this->getUrl('search', 'index') . '?tags=' . $value . '">' . $value . '</a>';
        }
        $products->color = implode(', ', $tmp);

        $reviews = DatabaseObject_ProductsReviews::GetProductReviews($this->db, $products->getId());

        $products->reviews = $reviews;
        // CustomControllerAction::pre($products->reviews);
        $this->view->products = $products;
        $this->view->page_title = $products->name;
        $cats = DatabaseObject_Products::GetCatProduct($this->db, $this->user->getId());
        $this->view->cats = $cats;
    }

    public function profileAction() {
        $cats = DatabaseObject_Products::GetCatProduct($this->db, $this->user->getId());
        $type = array();
        $type['one'] = DatabaseObject_Products::GetCountUser($this->db, $this->user->getId(), false, '1');
        $type['two'] = DatabaseObject_Products::GetCountUser($this->db, $this->user->getId(), false, '2');
        $type['three'] = DatabaseObject_Products::GetCountUser($this->db, $this->user->getId(), false, '3');
        $type['all'] = DatabaseObject_Products::GetCountUser($this->db, $this->user->getId());
        // CustomControllerAction::pre($type);
        $this->view->type = $type;


        $this->view->page_title = "Профиль мастера";
    }

    public function reviewsAction() {
        if ($this->getRequest()->isPost()) {
            $review = new DatabaseObject_ShopReviews($this->db);
            $review->user_id = Zend_Auth::getInstance()->getIdentity()->id;
            $review->shop_id = $this->user->getId();
            $review->type = $this->getRequest()->getPost('type');
            $review->text = $this->getRequest()->getPost('text');
            $review->date = date("Y-m-d H:i:s");

            // отправим уведомление о новом отзыве
            $userNotificationConfig = new DatabaseObject_NotificationSettings($this->db);
            $userNotificationConfig->load($this->user->getId(), 'idUser');

            if($userNotificationConfig && $userNotificationConfig->new_com == 1) {
                DatabaseObject_User::SendNotificationEmail($this->db, 'new_com', $this->user->getId());
            }
            
            $review->save();
        }

        $reviews = DatabaseObject_ShopReviews::GetShopReviews($this->db, $this->user->getId(), 1000, 0);
        if (isset(Zend_Auth::getInstance()->getIdentity()->id))
            $canPost = DatabaseObject_ShopReviews::CanPost($this->db, Zend_Auth::getInstance()->getIdentity()->id, $this->user->getId());
        else
            $canPost = 0;
        $this->view->reviews = $reviews;
        $this->view->canPost = $canPost;
        $this->view->page_title = "Отзывы о мастере";
    }

    public function policyAction() {
        $cats = DatabaseObject_Products::GetCatProduct($this->db, $this->user->getId());
        $type = array();
        $type['one'] = DatabaseObject_Products::GetCountUser($this->db, $this->user->getId(), '1');
        $type['two'] = DatabaseObject_Products::GetCountUser($this->db, $this->user->getId(), '2');
        $type['three'] = DatabaseObject_Products::GetCountUser($this->db, $this->user->getId(), '3');
        $type['all'] = DatabaseObject_Products::GetCountUser($this->db, $this->user->getId());
        //CustomControllerAction::pre($profile);
        $this->view->type = $type;
       

        $this->view->page_title = "Правила магазина";
    }

}
